package wang.hex.codetransfer.code;

import wang.hex.codetransfer.code.gui.SnapShot;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

/**
 * @Author wujie
 * @Class Reciver
 * @Description
 * @Date 2021/1/6 10:11
 */
public class Receiver {
    private int x;
    private int y;
    private int width;
    private int height;
    private int len;

    public Receiver(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }


    public ByteData doReceive() {
        BufferedImage image = SnapShot.snapShot(x, y, width, height);
        try {
            ImageIO.write(image, "jpg", new FileOutputStream("1.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = QRCoderGen.decodeBytes(image);
        return new ByteData(bytes);
    }


    public static class ByteData {
        private long pageNum;
        private int len;
        private byte[] data;

        ByteData(byte[] origin) {

            pageNum = BytesUtil.getLongFromBytes(origin, 0);
            len = BytesUtil.getIntFromBytes(origin, 8);
            if (len >= 0) {
                data = Arrays.copyOfRange(origin, 12, 12 + len);
            } else {
                data = null;
            }
        }

        public long getPageNum() {
            return pageNum;
        }

        public int getLen() {
            return len;
        }

        public byte[] getData() {
            return data;
        }

        @Override
        public String toString() {
            return "ByteData{" +
                    "pageNum=" + pageNum +
                    ", len=" + len +
                    ", data=" + Arrays.toString(data) +
                    '}';
        }
    }

}
